package com.nioEx;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOClient {

	public static void main(String[] args) throws IOException {

		Selector sel = Selector.open();

		ByteBuffer b = ByteBuffer.allocate(1024);

		ReadableByteChannel read = Channels.newChannel(System.in);

		SocketChannel sc = SocketChannel.open(new InetSocketAddress(
				"127.0.0.1", 6018));

		sc.configureBlocking(false);
		sc.register(sel, SelectionKey.OP_READ);

		b.put("hello".getBytes());
		b.flip();
		sc.write(b);
		b.clear();

		while (true) {

			if (sel.select() <= 0) {

				System.out.println(">>>>");
				continue;
			}
			Iterator<SelectionKey> iter = sel.selectedKeys().iterator();
			while (iter.hasNext()) {

				SelectionKey key = iter.next();

				iter.remove();

				handleKey(key);

			}

		}

	}

	public static void handleKey(SelectionKey key) throws IOException {

		if (key.isConnectable()) {
			System.out.println(">>>>>>NOW IS CONNECTING");
			key.interestOps(SelectionKey.OP_READ);

		}

		if (key.isReadable()) {
			ByteBuffer b = ByteBuffer.allocate(100);
			SocketChannel ss = (SocketChannel) key.channel();

			if (ss.read(b) > 0) {
				b.flip();
				byte[] a = new byte[b.limit()];
				b.get(a);
				System.out.println("Server >>" + new String(a));
				b.clear();

				key.interestOps(SelectionKey.OP_WRITE);

			}

		}

		if (key.isWritable()) {
			ByteBuffer b = ByteBuffer.allocate(100);
			SocketChannel ss = (SocketChannel) key.channel();

			b.put("good".getBytes());
			b.flip();
			ss.write(b);
			b.clear();

			key.interestOps(SelectionKey.OP_READ);
		}
	}
}
